Получить определенные значения из многомерного массива, привязанного к идентификатору

Возможно, название немного сбивает с толку, но позвольте мне попытаться объяснить.

У меня есть база данных (informix), и я использую PHP PDO, в этой базе данных есть таблица, содержащая таблицы стилей для страниц. Смотрите это так:

Специальный идентификатор, полная таблица стилей (как мы делаем это в файле CSS).

На данный момент я могу отображать записи в многомерном массиве (см. ниже код и вывод):

$query = $db -> prepare("select alpb_box_id, alpb_style::lvarchar as STYLESHEET  
from ao_link_page_boxes WHERE  alpb_li_id = 633 AND alpb_lngcode = '031' AND 
alpb_pageno = 1"); 

$query -> execute();

$result = array();

while($row = $query->fetch(PDO::FETCH_ASSOC)) {

$result[] = $row;
}
$db = null;

echo "<pre>";
print_r($result);
echo "</pre>";

И вывод:

Array
(
[0] => Array
(
[ALPB_BOX_ID] => TXT-633-P1B1
        [STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:Swis721 BT; font-size:69px; font-style:normal; font-variant:normal; font-weight:normal; height:75px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:hidden; overflow-y:hidden; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:0px; vertical-align:baseline; white-space:normal; width:793px; word-spacing:0px; z-index:auto;
    )

[1] => Array
    (
        [ALPB_BOX_ID] => TXT-633-P1B2
        [STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:\'Swis721 BT\'; font-size:16px; font-style:italic; font-variant:normal; font-weight:normal; height:197px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:hidden; overflow-y:hidden; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:absolute; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:75px; vertical-align:baseline; white-space:normal; width:717px; word-spacing:0px; z-index:auto;
    )

[2] => Array
    (
        [ALPB_BOX_ID] => IMG-633-P1B3
        [STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:\'Times New Roman\'; font-size:16px; font-style:normal; font-variant:normal; font-weight:normal; height:188px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:visible; overflow-y:visible; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:207px; vertical-align:baseline; white-space:normal; width:377px; word-spacing:0px; z-index:auto;
    )

[3] => Array
    (
        [ALPB_BOX_ID] => IMG-633-P1B4
        [STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:Times New Roman; font-size:16px; font-style:normal; font-variant:normal; font-weight:normal; height:188px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:visible; overflow-y:visible; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:0px; vertical-align:baseline; white-space:normal; width:377px; word-spacing:0px; z-index:auto;
    )

)

Теперь я пытаюсь получить от каждого идентификатора (например: TXT-633-P1B1) следующие стили:

высота: 75 пикселей; ширина: 793 пикселей; верх: 0 пикселей; и слева:0px;.

И сохраняйте их в результаты, чтобы я мог повторно использовать их и отображать их, когда это необходимо.

В этом случае я должен получить 4 идентификатора с 4 элементами стиля (включая количество пикселей).

Кто-нибудь знает, как это сделать. Надеюсь, я правильно объяснил свой вопрос.

Спасибо


Спасибо, это было очень полезно, у меня есть один вопрос.

Как я могу добавить эти значения в готовый div. Например:

<div id="TXT-633-P1B1" style="height:75px; width:793px; top:0px; left:0px;"></div>

И это для каждого идентификатора, который находится в этом массиве.

Спасибо, я действительно ценю это.


person udigital    schedule 17.10.2011    source источник


Ответы (1)


Попробуй это:

$new_styles = array();
$styles_to_collect = array('height', 'width', 'top', 'left');
foreach($result as $r)
{
        $new_entry = array();
        foreach($styles_to_collect as $stc)
        {
                preg_match('/[;\s]\s*'.$stc.':\s*([\d]+(px)?)([;\s]|$)/', $r['STYLESHEET'], $matches);
                $new_entry[$stc] = $matches[1];
        }
        $new_styles[$r['ALPB_BOX_ID']] = $new_entry;
}

производит ($new_styles):

Array
(
    [TXT-633-P1B1] => Array
        (
            [height] => 75px
            [width] => 793px
            [top] => 0px
            [left] => 0px
        )

    [TXT-633-P1B2] => Array
        (
            [height] => 197px
            [width] => 717px
            [top] => 75px
            [left] => 0px
        )

    [IMG-633-P1B3] => Array
        (
            [height] => 188px
            [width] => 377px
            [top] => 207px
            [left] => 0px
        )

    [IMG-633-P1B4] => Array
        (
            [height] => 188px
            [width] => 377px
            [top] => 0px
            [left] => 0px
        )

)

РЕДАКТИРОВАТЬ: по запросу ОП я добавляю больше к своему ответу. Чтобы использовать эти стили в контенте, вы можете сделать что-то вроде:

$content = '';
foreach($new_styles as $id=>$ns)
{
        $inline_styles = '';
        foreach($ns as $name=>$value) $inline_styles .= $name.': '.$value.'; ';
        $inline_styles = trim($inline_styles);
        $content .= '<div id="'.$id.'" style="'.$inline_styles."\"></div>\n";
}

Что установит $content в:

<div id="TXT-633-P1B1" style="height: 75px; width: 793px; top: 0px; left: 0px;"></div>
<div id="TXT-633-P1B2" style="height: 197px; width: 717px; top: 75px; left: 0px;"></div>
<div id="IMG-633-P1B3" style="height: 188px; width: 377px; top: 207px; left: 0px;"></div>
<div id="IMG-633-P1B4" style="height: 188px; width: 377px; top: 0px; left: 0px;"></div>
person ghbarratt    schedule 17.10.2011
comment
Спасибо, это было очень полезно, у меня есть один вопрос. Как я могу добавить эти значения в готовый div. Например: <div id="TXT-633-P1B1" style="height:75px; width:793px; top:0px; left:0px;"></div> И это для каждого идентификатора в этом массиве. Спасибо, я действительно ценю это. - person udigital; 18.10.2011
comment
@user999221 user999221 Я добавил больше к своему ответу - person ghbarratt; 18.10.2011
comment
Спасибо, я сам был рядом. У меня есть последний вопрос. Когда я хочу, чтобы значения были, например, такими же, как порядок массива выше: value[1] value[2] value[3] ..... Это не имеет ничего общего со стилями div, потому что они отлично работают, это что-то другое. Надеюсь, вы уловили мою мысль? Спасибо еще раз. - person udigital; 19.10.2011
comment
просто для ясности эти значения также можно использовать в списке (поэтому я добавил [] после них. - person udigital; 19.10.2011
comment
У меня уже есть следующий код: function flatten($array) { if (!is_array($array)) { return array($array); } $result = array(); foreach ($array as $value) { $result = array_merge($result, flatten($value)); } return $result; } $arr = $new_styles; foreach (flatten($arr) as $key=> $value) { echo "$key = $value <br />"; } Это дает мне ключ = значение, например: 0 = 75, 1 = 793. Теперь я хочу использовать ключ со значением: $value[$key], но это дает мне только массив результатов. - person udigital; 19.10.2011
comment
Хорошо, я понял, это было даже проще, чем я думал. Я только что сделал небольшой foreach, чтобы получить значение из опубликованного вами массива. Спасибо за вашу помощь. $arr = $new_styles; foreach ($arr as $value) { echo $value[top]; //and more} Я использую этот код, и он работает. - person udigital; 19.10.2011