0

我正在尝试根据用户指定的键打印值。我的 javascript 对象看起来像

$test={
"timed_out": false,
 "hits": {

    "hits": [
        {
            "_index": "test2",
            "_type": "news",
            "_source": {
                "partnerName": "Accountancy_Age",

                "entityCount": 4,
                "Categories": {
                    "Facets": [
                        {
                            "count": 1,
                            "entity": "Company",
                            "Company": [
                                {
                                    "Pearson_Plc-Sponsored_Adr": [
                                        {
                                            "count": 1,
                                            "entity": "Pearson"
                                        }
                                    ],
                                    "sector": "Communications",
                                    "ticker": "PSO",
                                    "entity": "Pearson Plc-Sponsored Adr",
                                    "type": "ADR"
                                }
                            ]
                        },
                        {
                            "CorporateAction": [
                                {
                                    "count": 2,
                                    "entity": "restructuring"
                                }
                            ],
                            "count": 2,
                            "entity": "CorporateAction"
                        },
                        {
                            "count": 1,
                            "entity": "Persons",
                            "Persons": [
                                {
                                    "count": 1,
                                    "entity": "Steven Pearson"
                                }
                            ]
                        }
                    ]
                },
                "Title": "PwC takes on major London oil refinery administration ",
                "Tags": "News",
                "ParentUrl": "http://www.accountancyage.com/feeds/rss/maxcontentwords/75/category/business-regulation",
                "Link": "http://www.accountancyage.com/aa/news/2141170/pwc-takes-major-london-oil-refinery-administration?WT.rss_f=Business+regulation&WT.rss_a=PwC+takes+on+major+London+oil+refinery+administration+",
                "SourceName": "Accountancy_Age",
                "SentimentResource": "neutral",
                "Content": "<div class=\"article_description\" algoscore=\"83\">\n <p algoscore=\"34\"><strong>LONDON'S BIGGEST </strong>oil refinery has been handed over to administrators from PwC by its Swiss parent company.</p>\n <p algoscore=\"37\">Petroplus, which refines 220,000 barrels a day from the Thames, was declared insolvent after the group suffered refinancing issues, a high cost base and high restructuring costs.</p>\n <p algoscore=\"35\">The business has around 60 employees, and supplies aronud a fifth of London and the south-east's 2,000 forecourts.</p>\n <p algoscore=\"40\">&quot;Our immediate priority is to continue to operate the Coryton refinery and the Teeside storage business, without disruption while the financial position is clarified and restructuring options are explored,&quot; said PwC joint administrator Steven Pearson.</p>\n <p algoscore=\"38\">&quot;Over coming days we intend to commence discussions with a number of parties including customers, employees, the creditors and the government to secure the future of the Coryton and Teesside sites.</p>\n</div>"
            }
        },
        {
            "_index": "test3",
            "_type": "news",

            "_source": {
                "partnerName": "propertyFile 7",
                "entityCount": 33,
                "Categories": {
                    "Types": {
                        "Facets": [
                            {
                                "count": 3,
                                "entity": "Company",
                                "Company": [
                                    {
                                        "sector": "Basic Materials",
                                        "ticker": "BHP",
                                        "entity": "Bhp Billiton Ltd-Spon Adr",
                                        "Bhp_Billiton_Ltd-Spon_Adr": [
                                            {
                                                "count": 1,
                                                "entity": "BHP Billiton Ltd"
                                            }
                                        ],
                                        "type": "ADR"
                                    },
                                    {
                                        "sector": "Communications",
                                        "ticker": "CHL",
                                        "entity": "China Mobile Ltd-Spon Adr",
                                        "type": "ADR",
                                        "China_Mobile_Ltd-Spon_Adr": [
                                            {
                                                "count": 1,
                                                "entity": "China Mobile"
                                            }
                                        ]
                                    },
                                    {
                                        "sector": "Energy",
                                        "Royal_Dutch_Shell_Plc-Adr": [
                                            {
                                                "count": 1,
                                                "entity": "Royal Dutch"
                                            }
                                        ],
                                        "ticker": "RDS/A",
                                        "entity": "Royal Dutch Shell Plc-Adr",
                                        "type": "ADR"
                                    }
                                ]
                            },
                            {
                                "count": 6,
                                "entity": "Country",
                                "Country": [
                                    {
                                        "region": "Asia",
                                        "Taiwan": [
                                            {
                                                "count": 1,
                                                "entity": "Taiwan"
                                            }
                                        ],
                                        "index": "TAIWAN TAIEX INDEX",
                                        "entity": "Taiwan",
                                        "currency": "Dollar (TWD)"
                                    },
                                    {
                                        "region": "Latin Americas",
                                        "index": "BRAZIL BOVESPA INDEX",
                                        "Brazil": [
                                            {
                                                "count": 1,
                                                "entity": "Brazil"
                                            }
                                        ],
                                        "entity": "Brazil",
                                        "currency": "Real (BRL)"
                                    },
                                    {
                                        "region": "East Europe",
                                        "index": "ISE NATIONAL 100 INDEX",
                                        "entity": "Turkey",
                                        "Turkey": [
                                            {
                                                "count": 1,
                                                "entity": "Turkey"
                                            }
                                        ],
                                        "currency": "Lira (TRY)"
                                    },
                                    {
                                        "region": "Europe",
                                        "index": "BLOOMBERG EUROPEAN 500 , Euro Stoxx 50 Pr",
                                        "entity": "Europe",
                                        "Europe": [
                                            {
                                                "count": 1,
                                                "entity": "Europe"
                                            }
                                        ],
                                        "currency": "Euro (EUR)"
                                    },
                                    {
                                        "region": "Asia",
                                        "index": "CSI 300 INDEX , SHANGHAI SE COMPOSITE , SHENZHEN SE COMPOSITE IX , SSE COMPONENT STOCK IX",
                                        "entity": "China",
                                        "China": [
                                            {
                                                "count": 2,
                                                "entity": "China"
                                            }
                                        ],
                                        "currency": "Yuan Renminbi (CNY)"
                                    }
                                ]
                            },
                            {
                                "AnalystLevel": [
                                    {
                                        "count": 1,
                                        "entity": "Buy"
                                    },
                                    {
                                        "count": 1,
                                        "entity": "hold"
                                    },
                                    {
                                        "count": 4,
                                        "entity": "market"
                                    }
                                ],
                                "count": 6,
                                "entity": "AnalystLevel"
                            },
                            {
                                "MoneyEvent": [
                                    {
                                        "count": 1,
                                        "entity": "Fund managers look at all sizes of companies and \r\nbase their selections on an index of companies that have paid at least $5 \r\nmillion in dividends over the past year."
                                    }
                                ],
                                "count": 1,
                                "entity": "MoneyEvent"
                            },
                            {
                                "DateEvent": [
                                    {
                                        "count": 1,
                                        "entity": "CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has \r\nalways been a challenge."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "Many, if not most, of these funds, it should be noted, were touted last \r\nyear as part of a growing group of \"low-volatility\" stock funds."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "The fund invests in companies \r\namong the top 100 dividend payers that have had payouts in the previous \r\nthree years."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "Yet the insurer is \r\nthe top holding in the SPDR S&P International Dividend ETF , paying a 5.38 \r\npercent dividend yield as of June 1."
                                    }
                                ],
                                "count": 4,
                                "entity": "DateEvent"
                            },
                            {
                                "count": 5,
                                "LocationEvent": [
                                    {
                                        "count": 1,
                                        "entity": "And some of the best sectors for high-dividend players are \r\nfar from Wall Street."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "But even as the euro zone beast continues to flair \r\nits nostrils and U.S. employment wheezes, there are stocks that are worthy \r\ncontenders, particularly ones that pay dividends."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "That's \r\nroughly twice the population of the U.S. already."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "These funds can be volatile and will be impacted if more European countries \r\nslip into recession, the U.S. falters or the Eurozone banking crisis isn't \r\nresolved."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "To find dividend players in emerging markets, I suggest the WisdomTree \r\nEmerging Markets Equity Income fund, which gives you exposure to China, \r\nBrazil, Taiwan and Turkey."
                                    }
                                ],
                                "entity": "LocationEvent"
                            },
                            {
                                "count": 3,
                                "CompanyEvent": [
                                    {
                                        "count": 1,
                                        "entity": "China Mobile, the largest cellphone carrier in the People's \r\nRepublic, has more than 600 million subscribers - and is growing."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "The Admiral Group, a U.K.-based \r\nauto insurance company, for example, is hardly in a league with the oil \r\nproducer Royal Dutch Shell in terms of name recognition."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "Then you'd want a \r\ncompany like BHP Billiton Ltd. ), one of the world's largest natural \r\nresources companies."
                                    }
                                ],
                                "entity": "CompanyEvent"
                            },
                            {
                                "count": 1,
                                "entity": "AnalystAction",
                                "AnalystAction": [
                                    {
                                        "count": 1,
                                        "entity": "Buy"
                                    }
                                ]
                            },
                            {
                                "count": 2,
                                "entity": "PercentEvent",
                                "PercentEvent": [
                                    {
                                        "count": 1,
                                        "entity": "Europe's largest oil producer reported \r\nthat its earnings were up 11 percent in the first quarter."
                                    },
                                    {
                                        "count": 1,
                                        "entity": "Shell, by the way, is no slouch in the dividend department either, paying \r\n5.53 percent as of the same date."
                                    }
                                ]
                            },
                            {
                                "count": 1,
                                "entity": "Person",
                                "Person": [
                                    {
                                        "count": 1,
                                        "entity": "John Wasik"
                                    }
                                ]
                            },
                            {
                                "count": 1,
                                "entity": "PersonEvent",
                                "PersonEvent": [
                                    {
                                        "count": 1,
                                        "entity": "By John Wasik"
                                    }
                                ]
                            }
                        ]
                    }
                },
                "Title": "Where in the world are dividends good?",
                "ParentUrl": "http://feeds.reuters.com/reuters/blogs/JohnWasik?format=xml",
                "Tags": "Blog",
                "Link": "http://www.reuters.com/article/2012/06/01/column-wasik-worlddividends-idUSL1E8H15SF20120601?feedType=RSS&feedName=everything&virtualBrandChannel=11563",
                "SourceName": "Reuters",
                "SentimentResource": "positive",
                "Content": "<span id=\"articleText\" algoscore=\"413\"><p></p><span class=\"focusParagraph\"></span><p>By <a href=\"http://blogs.reuters.com/search/journalist.php?edition=us&amp;n=john.wasik&amp;\">John Wasik</a></p><p>CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has always been a challenge. But even as the euro zone beast continues to flair its nostrils and U.S. employment wheezes, there are stocks that are worthy contenders, particularly ones that pay dividends. While they don't eliminate market risk, dividends can bolster total return in skittish equity markets. And some of the best sectors for high-dividend players are far from Wall Street.</p><p>For long-term investing, think commodities, energy, utilities and non-banking financial services. Banking is still touchy, but insurance is a safer bet.</p><p>Established, brand-name stocks often pay large dividends, but that doesn't mean they should dominate your portfolio. The Admiral Group, a U.K.-based auto insurance company, for example, is hardly in a league with the oil producer Royal Dutch Shell in terms of name recognition. Yet the insurer is the top holding in the SPDR S&amp;P International Dividend ETF , paying a 5.38 percent dividend yield as of June 1.</p><p>Shell, by the way, is no slouch in the dividend department either, paying 5.53 percent as of the same date. Europe's largest oil producer reported that its earnings were up 11 percent in the first quarter.</p><p>The international dividend strategy is often rooted in sectors in which profits are consistent and growing. That translates into steady dividend growth year after year, although the sectors that are favored for stock-price appreciation will vary.</p><p>Let's say you were long in commodities, which isn't a bad play considering the demand for raw materials from developing countries. Then you'd want a company like BHP Billiton Ltd. ), one of the world's largest natural resources companies. BHP mines aluminum, copper, coal, iron ore, nickel, silver and uranium and also has oil and gas reserves.</p><p>Another growth sector is telecommunications, particularly in emerging economies. China Mobile, the largest cellphone carrier in the People's Republic, has more than 600 million subscribers - and is growing. That's roughly twice the population of the U.S. already.</p><p>A key part of the global dividend strategy is to stay in sectors that are likely to continue dividend growth. That's why exchange-traded funds make the most sense when investing in these companies. The funds can hold broad indexes of dividend payers so you don't have to guess which companies will maintain or raise their payouts. ETFs also blunt risk, since unusually high dividends can be a sign of a company's financial distress.</p><p>To find dividend players in emerging markets, I suggest the WisdomTree Emerging Markets Equity Income fund, which gives you exposure to China, Brazil, Taiwan and Turkey. Fund managers look at all sizes of companies and base their selections on an index of companies that have paid at least $5 million in dividends over the past year. An alternative is the SPDR S&amp;P Emerging Markets Dividend ETF.</p><p>If you prefer a focus on more developed markets, then consider the iShares Dow Jones International Dividend Index ETF . The fund invests in companies among the top 100 dividend payers that have had payouts in the previous three years. A similar fund is the PowerShares International Dividend Achievers Portfolio.</p><p>Many, if not most, of these funds, it should be noted, were touted last year as part of a growing group of &quot;low-volatility&quot; stock funds. While I think that has been a misnomer because it implies that these vehicles won't be hit by general market declines - they certainly will - they deserve a place in your portfolio.</p><p>When selecting a global dividend-stock fund, keep in mind that they won't insulate you from market risk and they are not bond funds.</p><p>These funds can be volatile and will be impacted if more European countries slip into recession, the U.S. falters or the Eurozone banking crisis isn't resolved. They also are subject to sector risk. If they are over concentrated in say, energy, and that sector is sold off in a market correction, then you will see declines in share prices. Buy them to augment your current stock positions and to boost income, but they shouldn't be core holdings.</p></span>",
                "ContentHash": 783187784,
                "LinkObjects": {
                    "LinkObjects": [
                        {
                            "Link": "http://blogs.reuters.com/search/journalist.php?edition=us&amp;n=john.wasik&amp;",
                            "Object": "John Wasik"
                        }
                    ]
                }
            }
        }]}};

我在这里试图实现的是,如果用户指定 wordCount,那么它应该列出 json 中 wordCount 的所有出现。

我的代码看起来像,

$.ajax({
url:"/elasticsearch-head/lib/es/queryManipulate.php",
type: 'POST',
datatype: 'json',
data: { index: _index_select, category: _field_select},
success:function(jsonQuery)
    {
    //alert(jsonQuery);
    }

});




<?php
$index=$_POST["index"];
$selectCategory=$_POST["category"];
$url="http://localhost:9200/".$index."//_search";
$object=json_decode($_POST["field"]); 
$fields=array();
$fields = explode(',',$selectCategory);
$results = array();
for ($from = 0; $from <50; $from+=10){
$object->from=$from; 
$requestJSON=json_encode($object);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultJSON= curl_exec($ch); // equivalent of our JSON string that Ive shown above
$resultObject = json_decode($resultJSON);
curl_close ($ch);
$hits = $resultObject->hits->hits;
$m=0;
for($j=0 ; $j < sizeOf($hits) ; $j++){
    $result = array();
    for($i=0 ; $i< sizeOf($fields) ; $i++){
    if($fields[$i]=="Categories->Types->Facets")
            {               
                $source = $hits[$j]->_source->Categories->Types->Facets;
                //echo $m++ . ";" .sizeof($source)."<br>";
                for($k=0; $k < sizeof($source); $k++)
                {
                    //echo $fields[$i];
                    //echo json_encode($source[$k]->entity) ."<br><br>";
                    $result[$j]->{$fields[$i]} = json_encode($source[$k]->entity);
                    //echo $result[$j]->{$fields[$i]};
                }
            }
            else
            {
                echo "test1";
                $source = $hits[$j]->_source;
                $result[$j]->{$fields[$i]} = json_encode($source->{$fields[$i]});
            }       


    }


    $results=array_merge($results,$result);

}
   }

     for($j=0 ; $j < sizeOf($fields) ; $j++) {
 echo $fields[$j].",";
   }
   echo "<br>";
   for($j=0 ; $j < sizeOf($results) ; $j++) {
$result = $results[$j];
$line="";
for($i=0 ; $i< sizeOf($fields) ; $i++){
            #echo var_dump($result);
            $field = $fields[$i];
            $line.=$result->{$field}.",";
}
echo $line."<br>";
    }
    ?>

如果输入不是数组,这将起作用,如果我们给输入一个数组说 Company fpr exaample,并且我想输出该数组中列出的项目,我将如何处理?

4

1 回答 1

0

尝试这样的事情:

$output = null;
array_walk_recursive($array, "callback", $output);

function callback ($value, $key, &$output)
{
    if ($key == 'wordCount')
    {
        $output .= $value;
    }
}
于 2012-07-23T13:24:48.630 回答